import dayjs from 'dayjs'
import _ from 'lodash'
import { typeMap } from '@/config/typeMap'
import { getProvince } from '@/api/common'

let provincesObj = null
export let provices = () => {
  getProvince().then(function (res) {
    provincesObj = res.provinces
  })
}

let filters = {
  typeMap: (input, type) => typeMap[type][input],
  date: (input, type) => dayjs(input).format(type || 'YYYY-MM-DD HH:mm:ss'),
  limitTo: (input, limit) =>
    input && input.length > limit ? input.substr(0, limit) + '...' : input,
  provinceToName: (input) =>
    _.result(
      _.first(
        _.filter(provincesObj, function (item) {
          return item.id.toString() === input
        })
      ),
      'name'
    ),
}

export default (filterType) => {
  if (Object.prototype.hasOwnProperty.call(filters, filterType)) {
    return (input, type = undefined) => {
      return input === null ||
        input === undefined ||
        input === '' ||
        input === '--'
        ? input
        : filters[filterType](input, type)
    }
  } else {
    return (input) => input
  }
}
